package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("page")
    public R<Page<Category>> page(int page, int pageSize) {
        //1. 创建分页对象
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //2. 直接调用service查询
        categoryService.query()
                .orderByAsc("sort")
                .orderByDesc("update_time")
                .page(pageInfo);
        //3. 返回数据
        return R.success(pageInfo);
    }

    /**
     * 修改分类信息
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        //直接调用业务层修改操作
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据id删除分类
     */
    @DeleteMapping
    public R<String> deleteById(Long id) {
        categoryService.deleteById(id);
        return R.success("删除成功");
    }


    /**
     * 根据type类型查询分类列表
     */
    @GetMapping("list")
    public R<List<Category>> list(Integer type) {
        //1. 调用业务层查询
        List<Category> list = categoryService.query()
                .eq(type != null, "type", type)
                .orderByAsc("sort")
                .orderByDesc("update_time")
                .list();
        //2. 响应数据
        return R.success(list);
    }
}
